using System;
using System.Net;
using System.Net.NetworkInformation;

namespace Sunny.UI;

public static class Net
{
	public class PingResult
	{
		public bool Result
		{
			get
			{
				PingReply reply = Reply;
				if (reply == null)
				{
					return false;
				}
				return reply.Status == IPStatus.Success;
			}
		}

		public PingReply Reply { get; internal set; }

		public string Host { get; internal set; }

		public IPAddress Address { get; internal set; }

		public string Message { get; internal set; }

		internal PingResult(string host, PingReply reply)
		{
			Host = host;
			Reply = reply;
		}

		internal PingResult()
			: this(string.Empty, null)
		{
		}
	}

	public static PingResult Ping(string host, TimeSpan timeout)
	{
		IPAddress iPAddress = null;
		try
		{
			IPAddress[] hostAddresses = Dns.GetHostAddresses(host);
			if (hostAddresses.Length == 0)
			{
				return new PingResult(host, null)
				{
					Message = "无法解析IP地址"
				};
			}
			iPAddress = hostAddresses[0];
			using Ping ping = new Ping();
			PingOptions pingOptions = new PingOptions();
			pingOptions.DontFragment = true;
			byte[] array = "Hello SunnyUI, Let's have a Ping".ToEnBytes(32);
			PingReply pingReply = ping.Send(iPAddress, (int)timeout.TotalMilliseconds, array, pingOptions);
			string text = ((pingReply.RoundtripTime < 1) ? "<1ms" : $"={pingReply.RoundtripTime}ms");
			PingResult pingResult = new PingResult(host, pingReply);
			pingResult.Message = ((pingReply.Status == IPStatus.Success) ? $"{pingReply.Status}: 来自{iPAddress}的回复: 字节={array.Length} 时间{text} TTL={pingReply.Options.Ttl}" : $"{pingReply.Status}");
			pingResult.Address = iPAddress;
			return pingResult;
		}
		catch (Exception ex)
		{
			return new PingResult(host, null)
			{
				Message = ex.Message,
				Address = iPAddress
			};
		}
	}
}
